﻿using Max.PH5_2103A.Shopping.IRepository;
using Max.PH5_2103A.Shopping.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Max.PH5_2103A.Shopping.Service
{
    public class BaseService<T> : IBaseService<T>
    {

        IBaseRepository<T> _repository;

        public BaseService(IBaseRepository<T> repository)
        {
            _repository = repository;
        }

        public virtual int Delete(T entity)
        {
            _repository.Delete(entity);
            return 1;
        }

        public virtual int Delete(List<T> list)
        {
            _repository.Delete(list);
            return 1;
        }

        public IQueryable<T> GetAll()
        {
            return _repository.GetAll();
        }

        public IQueryable<T> GetAll(int pageIndex, int pageSize, out int total)
        {
            var data = _repository.GetAll();

            total = data.Count();

            data = data.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            return data.AsQueryable();
        }

        public IQueryable<T> GetAll(Func<T, bool> where, int pageIndex, int pageSize, out int total)
        {
            var data = _repository.GetAll().Where(where);

            total = data.Count();

            data = data.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            return data.AsQueryable();
        }

        public IQueryable<T> GetAll(Expression<Func<T, bool>> where, int pageIndex, int pageSize, out int total)
        {
            var data = _repository.GetAll().Where(where);

            total = data.Count();

            data = data.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            return data.AsQueryable();
        }

        public T GetFirstById(object id)
        {
            return _repository.GetFirstById(id);
        }

        public virtual int Insert(T entity)
        {
            _repository.Insert(entity);
            return 1;
        }

        public virtual int Insert(List<T> list)
        {
            _repository.Insert(list);
            return 1;
        }

        public virtual int Update(T entity)
        {
            _repository.Update(entity);
            return 1;
        }

        public virtual int Update(List<T> list)
        {
            _repository.Update(list);
            return 1;
        }
    }
}
